var express = require('express')
var router = express.Router()
var {cartmodel} = require('../database/model/clientModel')
router.post('/',(req,res)=>{ //加入购物车
  // console.log(req.body);
  let {userid,goodid} = req.body
  cartmodel.find({userid,goodid}).then(result=>{
    if(result.length==0){
      new cartmodel(req.body).save().then(result=>{ //新增一条新商品
        res.send({
          code:111,
          msg:'成功加入购物车'
        })
      })
      return
    }
    let {_id,count} = result[0]  //已有商品的购物车id
    count+=req.body.count  //更新已有商品数量
    cartmodel.updateOne({_id},{count}).then(result=>{
      res.send({
        code:111,
        msg:'成功更新购物车'
      })
    })
  })
})

router.get('/',(req,res)=>{ //获取用户购物车列表
  // console.log(req.headers);   //在后端某个接口中直接提取请求头配置
  let {userid} = req.query
  cartmodel.find({userid}).then(result=>{
    res.send({
      code:1,
      msg:'购物车加载成功',
      data:result
    })
  })
})

module.exports = router